package com.lmscn.lms.api.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.core.Controller;
import com.lmscn.lms.api.model.CourseBase;
import com.lmscn.lms.api.model.CourseLearningSetting;
import com.lmscn.lms.api.model.CourseStudent;
import com.lmscn.lms.api.model.Exam;
import com.lmscn.lms.api.model.Student;
import com.lmscn.lms.api.model.StudyFileCourseRecord;
import com.lmscn.lms.api.model.StudyFileStudyPlanExamRecord;
import com.lmscn.lms.api.model.StudyPlan;
import com.lmscn.lms.api.model.SysProperties;
import com.lmscn.lms.api.model.TestpaperResult;
import com.lmscn.lms.api.util.CommonUtil;
import com.lmscn.lms.api.util.JsonKit;
import com.lmscn.lms.commons.GlobalConst;


public class UserStudyController extends Controller {
	private final String COURSETYPE_REQUIRED = "1";      //必修课
	private final String COURSETYPE_OPTIONAL = "0";      //选修课
	private final int LEARNEDSTATUS_COMPLETED = 1;       //已完成
	private final int LEARNEDSTATUS_NOT_COMPLETED = 0;   //未完成
	
	
	public void userStudyReport() {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Long studentId = getParaToLong("studentId");
		String studyGroup = getPara("studyGroup");
		
//		Student student = null;
//		if (studentId==null) {
//			student = Student.dao.findByUserId(studentId);
//		}
		int study_plan_year = SysProperties.dao
				.getSysPropertiesByName(GlobalConst.STUDY_PLAN_YEAR);
		if (study_plan_year < 1) {
			study_plan_year = new Date().getYear() + 1900;
		}
		StudyPlan studyPlan = StudyPlan.dao
				.getStudyPlan(study_plan_year, studyGroup);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("name", studyPlan.getStr("name"));                         // 学习计划名称
		map.put("year", studyPlan.getStr("year"));                         // 年份
		map.put("period", studyPlan.getFloat("period"));                   // 学时要求
		map.put("credit", studyPlan.getFloat("credit"));                   // 学分要求
		map.put("electivePeriod", studyPlan.getFloat("optional_period"));  // 选修课学时要求
//		map.put("requiredPeriod", studyPlan.getFloat("required_period"));  // 必修课学时要求
		dataMap.put("studyPlan", map);
		
		
		
		long planId = studyPlan.getLong("id");
		//学习总时长:秒，需要在前台页面转换成分钟
		long studyTotalTime = CourseStudent.dao.getTotalCourseLearnedTime(studentId);
		dataMap.put("studyTotalTime", studyTotalTime);
		
		//最近学习的课程
		List<Map<String, Object>> dataMapList = new ArrayList<Map<String, Object>>();
		List<CourseBase> courseBaseList = CourseBase.dao.findLastLearnedCourseList(studentId, 15);
		for (CourseBase courseBase : courseBaseList) {
			Map<String, Object> courseMap = new HashMap<String, Object>();
//			courseBase.set("url", CommonUtil.getMediaUrl(courseBase));
			courseBase.set("small_img", courseBase.getStr("small_img"));
			courseBase.set("large_img", courseBase.getStr("small_img"));
			courseMap.put("courseBase", courseBase);
			courseMap.put("courseLesson", courseBase.getCourseLesson());
			courseMap.put("courseLearningSetting", courseBase.getCourseLearningSetting());
			dataMapList.add(courseMap);
		}
		dataMap.put("lastLearnedCourses", dataMapList);
		
		
		// 必修课已完成的学时
		double completeRequiredPeriod = StudyPlan.dao
				.getStudyCoursePeriodsInStudyplan(planId, studentId,
						COURSETYPE_REQUIRED, LEARNEDSTATUS_COMPLETED);
		// 必修课未完成的学时
		double incompleteRequiredPeriod = StudyPlan.dao.
				getStudyCoursePeriodsInStudyplan(planId, studentId,
						COURSETYPE_REQUIRED, LEARNEDSTATUS_NOT_COMPLETED);
		// 选修课已完成的学时
		double completeElectivePeriod = StudyPlan.dao
				.getStudyCoursePeriodsInStudyplan(planId, studentId,
						COURSETYPE_OPTIONAL, LEARNEDSTATUS_COMPLETED);
		// 选修课未完成的学时
		double incompleteElectivePeriod = StudyPlan.dao
				.getStudyCoursePeriodsInStudyplan(planId, studentId,
						COURSETYPE_OPTIONAL, LEARNEDSTATUS_NOT_COMPLETED);
		dataMap.put("completeRequiredPeriod", completeRequiredPeriod);
		dataMap.put("incompleteRequiredPeriod", incompleteRequiredPeriod);
		dataMap.put("completeElectivePeriod", completeElectivePeriod);
		dataMap.put("incompleteElectivePeriod", incompleteElectivePeriod);
		
		renderJson(JsonKit.mapToJson(dataMap, GlobalConst.DEFAULT_DEPTH));
	}
	
	
	public void userStudyStat() {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Long studentId = getParaToLong("studentId");
		String studyGroup = getPara("studyGroup");
		int year = getParaToInt("year");
		
		StudyPlan studyPlan = StudyPlan.dao.getStudyPlan(year, studyGroup);
		long studyPlanId = studyPlan.getLong("id");
		
		//查询学习计划课程--选修
		Map<String, Object> XstudyPlanCourseRecordListMap = getStudyFileCourseRecordList(studentId, studyPlanId, 0);
		List<StudyFileCourseRecord> XstudyPlanCourseRecordList = (List<StudyFileCourseRecord>)XstudyPlanCourseRecordListMap.get("list");
		dataMap.put("XstudyPlanCourseRecordList", XstudyPlanCourseRecordList);
		dataMap.put("Xtotal", XstudyPlanCourseRecordListMap.get("total"));
		
		//查询学习计划课程--必修
		Map<String, Object> BstudyPlanCourseRecordListMap = getStudyFileCourseRecordList(studentId, studyPlanId, 1);
		List<StudyFileCourseRecord> BstudyPlanCourseRecordList = (List<StudyFileCourseRecord>)BstudyPlanCourseRecordListMap.get("list");
		dataMap.put("BstudyPlanCourseRecordList", BstudyPlanCourseRecordList);
		dataMap.put("Btotal", BstudyPlanCourseRecordListMap.get("total"));
		
		
		int study_plan_year = SysProperties.dao
				.getSysPropertiesByName(GlobalConst.STUDY_PLAN_YEAR);
		if (study_plan_year < 1) {
			study_plan_year = new Date().getYear() + 1900;
		}
		
		//学习计划考试列表
		 Map<String, Object> studyPlanCourseExamRecordListMap =
				 getStudyFileStudyPlanExamRecordList(studentId, studyPlanId, Integer.valueOf(year));
		List<StudyFileStudyPlanExamRecord> studyPlanCourseExamRecordList = (List<StudyFileStudyPlanExamRecord>)studyPlanCourseExamRecordListMap.get("list");
		dataMap.put("studyPlanCourseExamRecordList", studyPlanCourseExamRecordList);
		dataMap.put("Etotal", studyPlanCourseExamRecordListMap.get("total"));
		dataMap.put("thisYear", study_plan_year);
		dataMap.put("year", year);
		
		Float total = Float.valueOf( XstudyPlanCourseRecordListMap.get("total").toString() )
				+ Float.valueOf( BstudyPlanCourseRecordListMap.get("total").toString() )
				+ Float.valueOf( studyPlanCourseExamRecordListMap.get("total").toString() );
		dataMap.put("total", total);
		
		SysProperties sysPropertiesExamPeriod = SysProperties.dao.findByName("exam_period");
		String exam_period = sysPropertiesExamPeriod.getStr("value");
		if (exam_period==null || "".equals(exam_period.trim()) ) {
			exam_period="20";
		}
		dataMap.put("exam_period", 20);
		
		renderJson(JsonKit.mapToJson(dataMap, GlobalConst.DEFAULT_DEPTH));
	}
	
	/**
	 * @param studentId
	 * @param studyPlanId
	 * @param courseType  0选修课  or 1必修课
	 * @return
	 */
	private Map<String, Object> getStudyFileCourseRecordList(Long studentId, Long studyPlanId, int courseType) {
		List<StudyFileCourseRecord> recordList = new ArrayList<StudyFileCourseRecord>();
		List<CourseStudent> courselist = CourseStudent.dao.findCourseStudentList(
				studentId, studyPlanId, "studyplan", -1, courseType);
		float total = 0f;
		
		for(int i = 0; i < courselist.size(); i++){
			StudyFileCourseRecord record = new StudyFileCourseRecord();
			CourseStudent courseStudent = courselist.get(i);
			Long courseId = courseStudent.getLong("course_id");
			CourseBase courseBase = CourseBase.dao.findById(courseId);
			CourseLearningSetting courseLearningSetting =
					CourseLearningSetting.dao.findByCourseId(courseId);
			
			record.setStudyPlanId(studyPlanId);
			record.setCourseName(courseBase.getStr("name"));
			record.setCoursePeriod(courseLearningSetting.getFloat("period"));
			record.setCourseStudentId(courseStudent.getLong("id"));
			record.setCourseStudent(courseStudent);
			record.setCourseType(courseStudent.getStr("course_type"));
			record.setFinishedTime(courseStudent.getDate("finished_time"));
			record.setLearnedStatus(courseStudent.getInt("learned_status"));
			record.setScore(courseStudent.getInt("score"));
			record.setSelectedTime(courseStudent.getDate("create_time"));
			record.setTeacherName(courseBase.getStr("teacher_name"));
			recordList.add(record);
			if (courseStudent.getInt("learned_status")==1) {
				total+=courseLearningSetting.getFloat("period");
			}
		}
		
		Map<String, Object> finalMap = new HashMap<String, Object>();
		finalMap.put("list", recordList);
		finalMap.put("total", total); 
		return finalMap;
	}
	
	
	/**
	 * 在学习档案中获取学员年度学习计划考试的记录列表
	 * @param studentId
	 * @param studyPlanId
	 * @param year
	 * @return
	 */
	public Map<String, Object> getStudyFileStudyPlanExamRecordList(Long studentId, Long studyPlanId, int year) {
		//获取学员已经参加的年度学习计划考试列表
		List<Exam> list = Exam.dao.getJoinedYearStudyPlanExamList(studentId, year);
		//学习计划内参加的课程考试
		List<StudyFileStudyPlanExamRecord> recordList = new ArrayList<StudyFileStudyPlanExamRecord>();
		Float total = 0f;
		if(list != null && list.size() > 0){
			for(Exam exam:list){
				StudyFileStudyPlanExamRecord record = new StudyFileStudyPlanExamRecord();
				record.setExamId(exam.getLong("id"));
				record.setExamName(exam.getStr("title"));
				record.setStudentId(studentId);
				record.setStudyPlanId(studyPlanId);
				
				long examId = exam.getLong("id");
				String targetType = exam.getStr("target_type");
				
				//已完成的考试
				TestpaperResult result = TestpaperResult.dao.
						getFinishedTestpaperResult(studentId, examId, targetType, 1, -1);
				//未提交答卷
				if(result == null){
					result = TestpaperResult.dao.
							getFinishedTestpaperResult(studentId, examId, targetType, 0, -1);
					record.setStatus("notsubmit");
					record.setSubmitTime(null);
					record.setExamScore(null);
				}
				//已提交答卷 
				else {
					TestpaperResult result2 = TestpaperResult.dao
							.findMaxScore(studentId, examId, targetType);
					int userScore = result2.getInt("score");
					int passScore = exam.getInt("pass_proportion");
					boolean passed = userScore > passScore;
					if (passed) {
						record.setStatus("passed");
						total += exam.getFloat("course_period");
					} else {
						record.setStatus("notpassed");
					}
					record.setSubmitTime(result.getTimestamp("end_time"));
					record.setExamScore(result.getInt("score"));
				}
				
				recordList.add(record);
				
			}
		}
		Map<String, Object> finalMap = new HashMap<String, Object>();
		finalMap.put("list", recordList);
		finalMap.put("total", total);
		return finalMap;
	}
	
}
